package com.jjiang.bbmall.order.listener;

import com.jjiang.bbmall.order.entity.OrderEntity;
import com.jjiang.bbmall.order.service.OrderService;
import com.jjiang.common.to.SeckillOrderTo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.io.IOException;

@RabbitListener(queues = "order.seckill.order.queue")
@Service
public class OrderSeckillListener {
    @Autowired
    OrderService orderService;

    @RabbitHandler
    public void listener(SeckillOrderTo seckillOrderTo, Channel channel, Message message) throws IOException {
        System.out.println("准备进行秒杀商品的订单创建：" + seckillOrderTo.getOrderSn());
        Boolean retry = true;
        try {
            retry = orderService.createSeckillOrder(seckillOrderTo);
        } catch (DuplicateKeyException e) {
            retry = false;
        } catch (Exception e) {
            // 有异常，消费失败，需要重试
            System.out.println("秒杀商品订单创建出错！" + e.getClass());
        }
        if (retry) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        } else {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
